import { createRouter, createWebHistory } from "vue-router";
import store from "../store/index.js";

const routes = [
  {
    path: "/",
    component: () => import("../views/Main.vue"),
    name: "main",
    redirect: "/home",
    // children: [
    //   {
    //     path: "/home",
    //     name: "home",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/home/Home.vue"),
    //   },
    //   {
    //     path: "/plccontent",
    //     name: "plccontent",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/plc/PlcContent.vue"),
    //   },
    //   {
    //     path: "/user",
    //     name: "user",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/user/User.vue"),
    //   },
    //   {
    //     path: "/page1",
    //     name: "page1",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/Page1.vue"),
    //   },
    //   {
    //     path: "/page2",
    //     name: "page2",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/Page2.vue"),
    //   },
    //   {
    //     path: "/page3",
    //     name: "page3",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/Page3.vue"),
    //   },
    //   {
    //     path: "/page4",
    //     name: "page4",
    //     meta: {
    //       keepAlive: true,
    //     },
    //     component: () => import("../views/Page4.vue"),
    //   },
    // ],
    // 存储动态路由
    children: [],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 检查请求路由是否存在
function checkRouter(path) {
  // 获取到所有路由路径并过滤
  let check = router.getRoutes().filter((route) => route.path == path).length;
  if (check) {
    return true;
  } else {
    return false;
  }
}

// 页面跳转路由守卫
router.beforeEach((to, from, next) => {
  // 跳转前先获取token并且存入到vuex
  store.commit("getToken");
  const token = store.state.token;
  // 如果没有token并且访问的不是login页面就跳转到login
  if (!token && to.name != "login") {
    next({ name: "login" });
    // 如果当前跳转路径不存在，就跳转到home页面
  } else if (!checkRouter(to.path)) {
    next({ name: "main" });
  } else {
    // next才可放行
    next();
  }
});
export default router;
